package com.zlyx.easy.netty.server.core;

import java.util.concurrent.TimeUnit;

import io.netty.bootstrap.*;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.timeout.IdleStateHandler;

public class NettyFactory extends Thread{

	private EventLoopGroup bossGroup;
	private EventLoopGroup workerGroup;
	private int port;
	private AbstractNettyServer<?> iServer;

	public NettyFactory(int port, AbstractNettyServer<?> iServer) {
		this.iServer = iServer;
		this.port = port;
	}
	
	public void run() {
        this.bossGroup = new NioEventLoopGroup(); //用来接收进来的连接
        this.workerGroup = new NioEventLoopGroup(); //用来处理已经被接收的连接
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast("idleStateHandler", new IdleStateHandler(60, 0, 0,TimeUnit.SECONDS));
                            socketChannel.pipeline().addLast("decoder", new ByteArrayDecoder());
                            socketChannel.pipeline().addLast("channelHandler", (ChannelHandler) iServer);
                            socketChannel.pipeline().addLast("encoder",new ByteArrayEncoder());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
 
            ChannelFuture cf = bootstrap.bind(port).sync();
            cf.channel().closeFuture().sync(); 
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

	public void close() {
		workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
	}
}